<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>考试管理</el-breadcrumb-item>
      <el-breadcrumb-item>试卷列表</el-breadcrumb-item>
    </el-breadcrumb>
    <br />

    <el-row>
      <el-col :span="14">
        <template>
          <el-form :inline="true" :model="examPage" class="demo-form-inline" style="width: 100%;">
            <el-form-item label="编号">
              <el-input v-model="examPage.examId" placeholder="编号" style="width: 140px;" clearable></el-input>
            </el-form-item>
            <el-form-item label="试卷名">
              <el-input v-model="examPage.examTitle" placeholder="试卷名称" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loadData">查询</el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-col>


      <el-col :span="8">
        <template>
          <el-row>
            <el-button icon="el-icon-plus" type="success" size="medium" round @click="handExamPaper()">手动生成试卷
            </el-button>
            <el-button icon="el-icon-time" type="primary" size="medium" round @click="randGenerateWin()">随机生成试卷
            </el-button>

          </el-row>
        </template>
        <br>
      </el-col>
    </el-row>


    <template>
      <el-table :data="examList" style="width: 100%">

        <el-table-column fixed="left" label="编号" width="90">
          <template slot-scope="x">
            <span style="margin-left: 10px">{{ x.row.examId }}</span>
          </template>
        </el-table-column>

        <el-table-column label="试卷名" width="260">
          <template slot-scope="x">
            <span>{{x.row.examTitle}}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="260">
          <template slot-scope="x">
            <span>{{x.row.examCreatetime}}</span>
          </template>
        </el-table-column>

        <el-table-column label="满分" width="230">
          <template slot-scope="x">
            <span>{{x.row.examFullscore}}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="科目类型" width="100">
          <template slot-scope="x">
            <span >{{x.row.subjectId}}</span>
          </template>
        </el-table-column> -->

        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="x">
            <el-button class="el-icon-view" size="mini" type="text" @click="previewPaper(x.$index, x.row)">预览试卷
            </el-button>
            <el-button class="el-icon-delete" size="mini" style="color: red;" type="text"
              @click="deletePaper(x.$index, x.row)">删除</el-button>
          </template>
        </el-table-column>



      </el-table>
      <div class="block">
        <!-- <span class="demonstration">完整功能</span> -->
        <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page="examPage.page"
          :page-sizes="[3, 5, 7]" :page-size="examPage.row" layout="total, sizes, prev, pager, next, jumper"
          :total="examPage.total">
        </el-pagination>
      </div>
    </template>

    <template>



      <!-- 试卷题目模态框 -->
      <el-dialog title="试卷生成" :visible="dialogTableVisible" :before-close="closeWin" width="60%">

        <template>
          <el-form ref="examForm" :inline="true" :model="examPaper" :rules="rules" class="demo-form-inline">
            <el-form-item label="试卷名称" prop="examTitle">
              <el-input v-model="examPaper.examTitle" placeholder="试卷名称"></el-input>
            </el-form-item>
            <el-form-item label="满分">
              <el-input v-model="examPaper.examFullscore" readonly="readonly"></el-input>
            </el-form-item>
            <el-form-item label="已选">
              <span>{{questionListSize}}</span>
            </el-form-item>

          </el-form>

        </template>


        <el-table ref="multipleTable" :row-key="getRowKey" :data="list" style="width: 100%"
          @select="handleSelectionChange">
          <el-table-column type="selection" width="55" :reserve-selection="true">

          </el-table-column>
          <el-table-column prop="questionId" label="编号" width="40">
            <template slot-scope="scope">{{ scope.row.questionId }}</template>
          </el-table-column>
          <el-table-column prop="questionTopic" label="题目" width="280">
            <template slot-scope="scope">{{ scope.row.questionTopic }}</template>
          </el-table-column>
          <el-table-column prop="questionCourse" label="科目类型" width="90">
            <template slot-scope="scope">{{ scope.row.questionCourse }}</template>
          </el-table-column>
          <el-table-column prop="questionType" label="题目类型" width="90">
            <template slot-scope="scope">{{ scope.row.questionType }}</template>
          </el-table-column>
          <el-table-column prop="questionScore" label="分数" width="90">
            <template slot-scope="scope">{{ scope.row.questionScore }}</template>
          </el-table-column>
          <el-table-column prop="questionAnswer" label="答案" width="60">
            <template slot-scope="scope">{{ scope.row.questionAnswer }}</template>
          </el-table-column>
        </el-table>
        <div class="block">
          <!-- <span class="demonstration">完整功能</span> -->
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="questionPage.page" :page-sizes="[3, 5, 7]" :page-size="questionPage.row"
            layout="total, sizes, prev, pager, next, jumper" :total="questionPage.total">
          </el-pagination>
        </div>

        <br />
        <el-button icon="el-icon-plus" type="success" size="medium" round @click="saveSubmit('examForm')">确认</el-button>
        <el-button icon="el-icon-delete" type="danger" size="medium" round @click="resetList">重选</el-button>
      </el-dialog>

      <!-- 预览试卷模态框 -->
      <el-dialog title="预览试卷" :visible="previewVisible" :before-close="closeWin" width="60%">

        <template>

          <el-form ref="form" label-width="80px">
            <!-- <span> -->
            <!-- <h3 style="margin: 0px;padding: 0px;">一、单选题</h3> -->
            <!-- </span><br /> -->
            <div v-for="(questionI,index) in previewList" :key="index">
              <span v-if="questionI.questionType == '单选题'">
                <el-form-item>
                  <span>{{index+1}}. &nbsp; (单选题){{questionI.questionTopic}}</span><br />

                  <!-- <el-radio-group> -->
                  <input type="radio" :name="index" value="A" />A.
                  {{questionI.questionA}}<br />
                  <input type="radio" :name="index" value="B" />B.
                  {{questionI.questionB}}<br />
                  <input type="radio" :name="index" value="C" />C.
                  {{questionI.questionC}}<br />
                  <input type="radio" :name="index" value="D" />D.
                  {{questionI.questionD}}<br />


                </el-form-item>
              </span>
              <span v-else-if="questionI.questionType == '判断题'">
                <el-form-item>
                  <span>{{index+1}}. &nbsp; (判断题) {{questionI.questionTopic}}</span><br />
                  <!-- <el-radio-group> -->
                  <input type="radio" :name="index" value="√" />√
                  <input type="radio" :name="index" value="×" />×

                  <!-- <el-radio lable="booleanTrue" name="booleanAnswer">√</el-radio>
                    <el-radio lable="booleanFalse" name="booleanAnswer">×</el-radio> -->
                  <!-- </el-radio-group> -->
                </el-form-item>
              </span>

            </div>

            <!-- <span>
              <h3 style="margin: 0px;padding: 0px;">二、判断题</h3>
            </span><br />
            <div v-for="(questionI,index) in previewList" style="margin: 0 0 0 0;"> -->


            <!-- </div> -->

          </el-form>

        </template>
      </el-dialog>

      <!-- 随机生成试卷 -->
      <el-dialog title="随机生成" :visible="randGenerateVisible" width="28%" :before-close="closeWin">
        <el-form :inline="true" :model="examPaper" ref="ruleForm" :rules="rules" class="demo-form-inline"
          label-width="90px">
          <el-form-item label="试卷名称" prop="examTitle">
            <el-input v-model="examPaper.examTitle" placeholder="试卷名称" clearable></el-input>
          </el-form-item>

          <el-form-item label="单选题" prop="radioNumber">
            <el-input v-model.number="examPaper.radioNumber" placeholder="单选题个数" clearable></el-input>
          </el-form-item>
          <el-form-item label="判断题" prop="booleanNumber">
            <el-input v-model.number="examPaper.booleanNumber" placeholder="判断题题个数" clearable></el-input>
          </el-form-item>

          <el-form-item style="align-items: auto;">
            <el-button type="primary" @click="randGeneratePaper('ruleForm')">生成</el-button>
          </el-form-item>

        </el-form>

      </el-dialog>

    </template>
  </div>
</template>

<script>
  // 导入工具类
  import myUtil from "../util/MyUtil.js"

  export default {
    data() {
      return {
        form: [{
          radioAnswer: "",
          booleanAnswer: "",
        }],
        // 随机生成表单验证
        rules: {
          radioNumber: [{
              required: true,
              message: "请输入单选题个数",
              trigger: 'blur'
            },
            {
              type: "number",
              min: 1,
              max: 9,
              message: "最小 1 最大 9",
              trigger: 'blur'
            }
          ],
          booleanNumber: [{
              required: true,
              message: "请输入判断题个数",
              trigger: 'blur'
            },
            {
              type: "number",
              min: 1,
              max: 9,
              message: "最小 1 最大 9",
              trigger: 'blur'
            }
          ],
          examTitle: [{
            required: true,
            message: "请输入试卷名称",
            trigger: 'blur'
          }],
          examId: [{
            required: false,
          }, {
            type: "number",
            message: "最小 1 最大 9",
            trigger: 'blur'
          }]
        },
        examPaper: { // 试卷对象
          examId: 0,
          examTitle: "",
          examCreateTime: "",
          examFullscore: 100,
          subjectId: null,
          examList: [],
          radioNumber: '',
          booleanNumber: ''
        },
        question: { // 题目对象
          questionId: 0,
          questionTopic: "",
          questionCourse: "",
          questionDifficulty: "",
          questionA: "",
          questionB: "",
          questionC: "",
          questionD: "",
          questionScore: 10,
          questionAnswer: "",
          questionType: "",
          subjectId: 1
        },
        dialogTableVisible: false, // 模态框显示
        list: [], // 所有题目列表
        questionList: [], // 题目列表
        questionListSize: 0,
        questionPage: { // 题目分页
          page: 1,
          row: 5,
          total: 0
        },
        examList: [], // 试卷列表
        examPage: { // 试卷分页
          page: 1,
          row: 5,
          total: 0,
          examId: null,
          examTitle: ''
        },
        previewList: [],
        // 预览试卷模态框
        previewVisible: false,
        // 随机生出试卷模态框
        randGenerateVisible: false
      }
    },
    methods: {
      onSubmit() {
        console.log('submit!');
      },
      handleEdit(index, row) {
        console.log(index, row);
      },
      handleDelete(index, row) {
        console.log(index, row);
      },
      // 手动生成试卷
      // 加载所有题目信息
      handExamPaper() {
        this.dialogTableVisible = true;
        var self = this;
        $.ajax({
          url: myUtil.url + "/question/getAll",
          type: "get",
          data: self.questionPage,
          dataType: "json",
          success: function(rs) {
            // console.log(rs);
            self.list = rs.list;
            self.questionPage.total = rs.total;
            //self.$refs.multipleTable.toggleRowSelection(self.list[0],true);
            // console.log(self.questionList)
            // 回显选中的数据
            for (var i = 0; i < self.questionList.length; i++) {
              self.$refs.multipleTable.toggleRowSelection(self.questionList[i], true);
            }
            // console.log(self.$refs.multipleTable)
            // console.log("成功");
          },
          error: function(rs) {
            // console.log(rs);
            console.log("生成失败");
          }
        });

      },
      // 获取当前行的主键 用做数据回显的选中
      getRowKey(row) {
        return row.questionId;
      },
      // 关闭所有模态框
      closeWin() {
        this.dialogTableVisible = false;
        this.previewVisible = false;
        this.randGenerateVisible = false;
        // console.log(this.questionList);
        // console.log(this.form);
      },
      // 新增手动试卷
      saveSubmit(formName) {
        var self = this;
        // 表单验证
        self.$refs[formName].validate((valid) => {
          if (valid) {
            // self.$message("成功");
            self.examPaper.examList = self.questionList;
            $.ajax({
              url: myUtil.url + "/exampaper/generatePaper",
              type: "post",
              dataType: "json",
              data: JSON.stringify(self.examPaper),
              contentType: "application/json",
              success: function(rs) {
                if (rs.info == "新增成功" ) {
                  self.dialogTableVisible = false;
                  self.$message(rs.info);
                  self.examPage.examTitle = null;
                  self.loadData();
                } else {
                  self.$message(rs.info);
                }
                // console.log("success");
              },
              error: function(rs) {
                console.log("error");
              }
            });
          } else {
            // console.log('error submit!!');
            self.$message("试卷名称必填");
            return false;
          }
        });

        // console.log(self.examPaper)



        // console.log(this.questionList);
      },
      // 保存表格选中的数据
      handleSelectionChange(val, row) {
        // console.log(val);
        // console.log(row);
        if (val.includes(row)) {
          this.questionList.push(row);
        } else {
          var index = this.questionList.indexOf(row);
          this.questionList.splice(index, 1);
        }
        this.questionListSize = this.questionList.length;

        // console.log("1111111");
        // console.log(this.questionList);
      },
      // 当前页显示几条
      handleSizeChange(val) {
        this.questionPage.row = val;
        this.handExamPaper();
        // console.log(`每页 ${val} 条`);
      },
      // 当前第几页
      handleCurrentChange(val) {
        this.questionPage.page = val;
        this.handExamPaper();
        // console.log(`当前页: ${val}`);
      },
      // 加载所有试卷信息
      loadData() {
        var self = this;
        $.ajax({
          url: myUtil.url + "/exampaper/list",
          type: "get",
          data: self.examPage,
          dataType: "json",
          success: function(rs) {
            // console.log(rs);
            self.examList = rs.list;
            self.examPage.total = rs.total;
            // self.$message(rs.info);
            // console.log("加载成功");
          },
          error: function(rs) {
            // console.log(rs);
            // console.log("加载失败");
          }
        });
      },
      // 试卷页显示多少条数据
      sizeChange(val) {
        this.examPage.row = val;
        this.loadData();
      },
      // 试卷页当前第几页
      currentChange(val) { //
        this.examPage.page = val;
        this.loadData();
      },
      // 随机生成试卷窗口
      randGenerateWin() {
        this.randGenerateVisible = true;

        // 获取选择的答案
        // var dd = $("input[name=1]:checked").val()+"，"
      },
      // 随机生成试卷提交
      randGeneratePaper(formName) {
        // console.log("提交");
        var self = this;
        self.$refs[formName].validate((valid) => {
          if (valid) {

            let examNumber = Number.parseInt(self.examPaper.radioNumber) + Number.parseInt(self.examPaper
              .booleanNumber);
            console.log(examNumber);
            if (examNumber == 10) {
              // self.$alert("等于");
              $.ajax({
                url: myUtil.url + "/exampaper/randGeneratePaper",
                type: "post",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify(self.examPaper),
                success: function(rs) {
                  if (rs.info == "success") {
                    self.$message("新增成功");
                    // 关闭模态框
                    self.randGenerateVisible = false;
                    self.examPaper.examTitle = null;
                    // 刷新页面
                    self.loadData();
                  }
                  // console.log("success");
                },
                error: function(rs) {
                  console.log("error");
                }
              });
            } else {
              self.$alert("推荐 选择+判断 共10题");
            }
          } else {
            // console.log('error submit!!');
            return false;
          }
        });
      },
      // 预览试卷,加载当前选择试卷信息
      previewPaper(index, row) {
        this.previewVisible = true;
        var self = this;
        // console.log(row);
        $.ajax({
          url: myUtil.url + "/exampaper/previewPaper",
          type: "get",
          data: {
            "examId": row.examId
          },
          dataType: "json",
          success: function(rs) {
            // console.log(rs.list);
            self.previewList = rs.list;
            // console.log(self.previewList[0]);
          },
          error: function(rs) {

          }
        });
      },
      // 重置已选题目
      resetList() {
        var self = this;
        // 重置已选题目

        // console.log("已选"+self.questionList.length);
        for (var i = 0; i < self.questionList.length; i++) {
          self.$refs.multipleTable.toggleRowSelection(self.questionList[i], false);
        }
        self.questionList.splice(0, self.questionList.length);
        self.questionListSize = 0;
        // console.log("已选"+self.questionList.length);
        // self.handExamPaper();
      },
      deletePaper(index, row) {
        // console.log("删除功能"+row.examId);
        var self = this;
        self.$confirm('此操作将删除该试卷, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          $.ajax({
            url: myUtil.url + "/exampaper/deletePaper",
            type: "post",
            dataType: "json",
            data: JSON.stringify(row.examId),
            contentType: "application/json",
            success: function(rs) {
              if (rs.info == "success") {
                self.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                self.loadData();
              }
            },
            error: function(rs) {
              self.$message({
                type: 'error',
                message: '删除失败!'
              });
            }
          });
        }).catch(() => {
          self.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    // 挂载函数
    mounted() {
      this.loadData();
    }
  }
</script>

<style>
</style>
